<script setup>
import { computed, nextTick, ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '请输入...',
  },
  placeholderColor: {
    type: String,
    default: '#999',
  },
})

const emit = defineEmits(['update:modelValue', 'focus', 'blur'])

const inputContainer = ref(null)
const isFocused = ref(false)
const cursorPosition = ref(0)
const textSpan = ref(null)
const cursorIndex = ref(props.modelValue.length) // 初始设置为字符串末尾

const displayValue = computed(() => props.modelValue)

// 计算光标位置
async function calculateCursorPosition() {
  await nextTick()
  // 这里可以添加更精确的光标位置计算
  cursorPosition.value = props.modelValue.length * 8 // 简单估算，实际应根据字体大小调整
}

// 计算点击位置对应的字符索引
function getCursorIndexFromClick(clickX) {
  if (!textSpan.value || !textContainer.value) { return props.modelValue.length }

  const containerRect = textContainer.value.getBoundingClientRect()
  const relativeX = clickX - containerRect.left
  const text = props.modelValue

  // 创建临时span用于测量每个字符的位置
  const tempSpan = document.createElement('span')
  tempSpan.style.visibility = 'hidden'
  tempSpan.style.position = 'absolute'
  tempSpan.style.whiteSpace = 'pre'
  tempSpan.style.font = window.getComputedStyle(textSpan.value).font
  document.body.appendChild(tempSpan)

  // 找到点击位置对应的字符索引
  let index = 0
  let width = 0
  tempSpan.textContent = ''

  for (let i = 0; i <= text.length; i++) {
    tempSpan.textContent = text.substring(0, i)
    const currentWidth = tempSpan.offsetWidth

    if (currentWidth >= relativeX) {
      // 判断点击位置更靠近前一个字符还是后一个字符
      const prevDiff = relativeX - width
      const nextDiff = currentWidth - relativeX
      index = prevDiff < nextDiff ? i - 1 : i
      break
    }

    width = currentWidth
    index = i
  }

  document.body.removeChild(tempSpan)
  return Math.max(0, Math.min(index, text.length))
}

async function handleFocus() {
  if (!isFocused.value) {
    isFocused.value = true
    emit('focus')
    await calculateCursorPosition()
  }
}

function handleClick(event) {
  const clickX = event.clientX
  const newIndex = getCursorIndexFromClick(clickX)
  cursorIndex.value = newIndex
  console.log('点击位置》', clickX, '》当前位置》', cursorIndex.value)
  calculateCursorPosition(newIndex)
  handleFocus()
}

function handleBlur() {
  isFocused.value = false
  emit('blur')
}

watch(() => props.modelValue, calculateCursorPosition)

defineExpose({
  focus: handleFocus,
  blur: handleBlur,
})
</script>

<template>
  <div
    ref="inputContainer"
    class="custom-input" :class="[{ 'custom-input--focused': isFocused }]"
    tabindex="0"
    @click="handleClick"
  >
    <span class="custom-input__content">
      <span class="custom-input__text">{{ displayValue }}</span>
      <span
        v-if="isFocused"
        class="custom-input__cursor"
        :style="{ left: `${cursorPosition}px` }"
      />
    </span>
    <span v-if="!modelValue && !isFocused" class="custom-input__placeholder">
      {{ placeholder }}
    </span>
  </div>
</template>

<style scoped>
.custom-input {
  min-height: 40px;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  background-color: white;
  cursor: text;
  outline: none;
  position: relative;
}

.custom-input--focused {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.custom-input__content {
  position: relative;
  display: inline-block;
}

.custom-input__text {
  white-space: pre;
}

.custom-input__placeholder {
  color: v-bind('props.placeholderColor');
  position: absolute;
  left: 12px;
}

.custom-input__cursor {
  position: absolute;
  top: 0;
  width: 2px;
  height: 20px;
  background-color: #409eff;
  animation: blink 1s step-end infinite;
}

@keyframes blink {
  from,
  to {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
</style>
